package com.warehouse.service.impl;

import com.warehouse.dto.OrderDTO;
import com.warehouse.dto.OrderDetailDTO;
import com.warehouse.entity.Customer;
import com.warehouse.entity.Order;
import com.warehouse.entity.OrderDetail;
import com.warehouse.entity.Product;
import com.warehouse.entity.StockOut;
import com.warehouse.mapper.OrderDetailMapper;
import com.warehouse.mapper.OrderMapper;
import com.warehouse.mapper.StockOutMapper;
import com.warehouse.service.CustomerService;
import com.warehouse.service.OrderService;
import com.warehouse.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StockOutMapper stockOutMapper;

    @Override
    public List<Order> getAllOrders() {
        return orderMapper.selectAll();
    }

    @Override
    public List<OrderDTO> getAllOrdersWithDetails() {
        List<Order> orders = orderMapper.selectAll();
        List<OrderDTO> orderDTOs = new ArrayList<>();
        
        for (Order order : orders) {
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setId(order.getId());
            orderDTO.setOrderNumber(order.getOrderNumber());
            orderDTO.setCustomer(order.getCustomer());
            orderDTO.setCustomerPhone(order.getCustomerPhone());
            orderDTO.setCustomerAddress(order.getCustomerAddress());
            orderDTO.setTotalAmount(order.getTotalAmount());
            orderDTO.setStatus(order.getStatus());
            orderDTO.setOperator(order.getOperator());
            orderDTO.setRemark(order.getRemark());
            orderDTO.setOrderTime(order.getOrderTime());
            
            // 加载订单详情
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
            List<OrderDetailDTO> detailDTOs = orderDetails.stream()
                    .map(detail -> {
                        OrderDetailDTO dto = new OrderDetailDTO();
                        dto.setId(detail.getId());
                        dto.setOrderId(detail.getOrderId());
                        dto.setProductId(detail.getProductId());
                        dto.setProductName(detail.getProductName());
                        dto.setSpecification(detail.getSpecification());
                        dto.setQuantity(detail.getQuantity());
                        dto.setUnitPrice(detail.getUnitPrice());
                        dto.setTotalPrice(detail.getTotalPrice());
                        dto.setUnit(detail.getUnit());
                        return dto;
                    })
                    .collect(Collectors.toList());
            
            orderDTO.setOrderDetails(detailDTOs);
            orderDTOs.add(orderDTO);
        }
        
        return orderDTOs;
    }

    @Override
    public OrderDTO getOrderWithDetailsById(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return null;
        }
        
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setId(order.getId());
        orderDTO.setOrderNumber(order.getOrderNumber());
        orderDTO.setCustomer(order.getCustomer());
        orderDTO.setCustomerPhone(order.getCustomerPhone());
        orderDTO.setCustomerAddress(order.getCustomerAddress());
        orderDTO.setTotalAmount(order.getTotalAmount());
        orderDTO.setStatus(order.getStatus());
        orderDTO.setOperator(order.getOperator());
        orderDTO.setRemark(order.getRemark());
        orderDTO.setOrderTime(order.getOrderTime());
        orderDTO.setCreatedTime(order.getCreatedTime());
        orderDTO.setUpdatedTime(order.getUpdatedTime());
        
        // 加载订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
        List<OrderDetailDTO> detailDTOs = orderDetails.stream()
                .map(detail -> {
                    OrderDetailDTO dto = new OrderDetailDTO();
                    dto.setId(detail.getId());
                    dto.setOrderId(detail.getOrderId());
                    dto.setProductId(detail.getProductId());
                    dto.setProductName(detail.getProductName());
                    dto.setSpecification(detail.getSpecification());
                    dto.setQuantity(detail.getQuantity());
                    dto.setUnitPrice(detail.getUnitPrice());
                    dto.setTotalPrice(detail.getTotalPrice());
                    dto.setUnit(detail.getUnit());
                    return dto;
                })
                .collect(Collectors.toList());
        
        orderDTO.setOrderDetails(detailDTOs);
        return orderDTO;
    }

    @Override
    public Order getOrderById(Long id) {
        return orderMapper.selectById(id);
    }

    @Override
    public Order getOrderByOrderNumber(String orderNumber) {
        return orderMapper.selectByOrderNumber(orderNumber);
    }

    @Override
    public List<Order> getOrdersByCustomer(String customer) {
        return orderMapper.selectByCustomer(customer);
    }

    @Override
    public List<Order> getOrdersByStatus(String status) {
        return orderMapper.selectByStatus(status);
    }

    @Override
    public List<Order> getOrdersByDateRange(LocalDateTime startTime, LocalDateTime endTime) {
        return orderMapper.selectByDateRange(startTime, endTime);
    }

    @Override
    @Transactional
    public OrderDTO createOrder(OrderDTO orderDTO) {
        // 生成订单号
        orderDTO.setOrderNumber(generateOrderNumber());
        orderDTO.setStatus("PENDING");
        orderDTO.setOrderTime(LocalDateTime.now());

        // 处理新客户信息
        if (orderDTO.getNewCustomer() != null) {
            // 检查客户是否已存在
            List<Customer> existingCustomers = customerService.getCustomersByName(orderDTO.getNewCustomer().getCustomerName());
            boolean customerExists = existingCustomers.stream()
                    .anyMatch(c -> c.getCustomerName().equals(orderDTO.getNewCustomer().getCustomerName()) &&
                            (c.getPhone() == null || c.getPhone().equals(orderDTO.getNewCustomer().getPhone())));
            
            if (!customerExists) {
                // 创建新客户
                Customer newCustomer = new Customer();
                newCustomer.setCustomerName(orderDTO.getNewCustomer().getCustomerName());
                newCustomer.setPhone(orderDTO.getNewCustomer().getPhone());
                newCustomer.setAddress(orderDTO.getNewCustomer().getAddress());
                newCustomer.setStatus("ACTIVE");
                
                customerService.createCustomer(newCustomer);
            }
        }

        // 创建订单
        Order order = new Order();
        order.setOrderNumber(orderDTO.getOrderNumber());
        order.setCustomer(orderDTO.getCustomer());
        order.setCustomerPhone(orderDTO.getCustomerPhone());
        order.setCustomerAddress(orderDTO.getCustomerAddress());
        order.setStatus(orderDTO.getStatus());
        order.setOperator(orderDTO.getOperator());
        order.setRemark(orderDTO.getRemark());
        order.setOrderTime(orderDTO.getOrderTime());

        // 计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        if (orderDTO.getOrderDetails() != null) {
            for (OrderDetailDTO detailDTO : orderDTO.getOrderDetails()) {
                Product product = productService.getProductById(detailDTO.getProductId());
                if (product != null) {
                    BigDecimal unitPrice = product.getPrice() != null ? product.getPrice() : BigDecimal.ZERO;
                    BigDecimal totalPrice = unitPrice.multiply(new BigDecimal(detailDTO.getQuantity()));
                    detailDTO.setUnitPrice(unitPrice);
                    detailDTO.setTotalPrice(totalPrice);
                    totalAmount = totalAmount.add(totalPrice);
                }
            }
        }
        order.setTotalAmount(totalAmount);
        orderDTO.setTotalAmount(totalAmount);

        // 保存订单
        orderMapper.insert(order);
        orderDTO.setId(order.getId());

        // 保存订单详情
        if (orderDTO.getOrderDetails() != null) {
            List<OrderDetail> orderDetails = orderDTO.getOrderDetails().stream()
                    .map(detailDTO -> {
                        OrderDetail detail = new OrderDetail();
                        detail.setOrderId(order.getId());
                        detail.setProductId(detailDTO.getProductId());
                        detail.setProductName(detailDTO.getProductName());
                        detail.setSpecification(detailDTO.getSpecification());
                        detail.setQuantity(detailDTO.getQuantity());
                        detail.setUnitPrice(detailDTO.getUnitPrice());
                        detail.setTotalPrice(detailDTO.getTotalPrice());
                        detail.setUnit(detailDTO.getUnit());
                        return detail;
                    })
                    .collect(Collectors.toList());

            orderDetailMapper.insertBatch(orderDetails);
        }

        // 订单创建成功后，自动创建出库记录
        createStockOutRecordsFromOrder(order.getId(), orderDTO.getOrderDetails());

        return orderDTO;
    }

    @Override
    @Transactional
    public Order updateOrder(Order order) {
        // 获取现有订单信息
        Order existingOrder = orderMapper.selectById(order.getId());
        if (existingOrder == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 合并更新字段，保留原有字段
        if (order.getCustomer() != null) {
            existingOrder.setCustomer(order.getCustomer());
        }
        if (order.getCustomerPhone() != null) {
            existingOrder.setCustomerPhone(order.getCustomerPhone());
        }
        if (order.getCustomerAddress() != null) {
            existingOrder.setCustomerAddress(order.getCustomerAddress());
        }
        if (order.getTotalAmount() != null) {
            existingOrder.setTotalAmount(order.getTotalAmount());
        }
        if (order.getStatus() != null) {
            existingOrder.setStatus(order.getStatus());
        }
        if (order.getOperator() != null) {
            existingOrder.setOperator(order.getOperator());
        }
        if (order.getRemark() != null) {
            existingOrder.setRemark(order.getRemark());
        }
        
        // 更新修改时间
        existingOrder.setUpdatedTime(LocalDateTime.now());
        
        orderMapper.update(existingOrder);
        return existingOrder;
    }

    @Override
    @Transactional
    public OrderDTO updateOrder(OrderDTO orderDTO) {
        // 获取现有订单信息
        Order existingOrder = orderMapper.selectById(orderDTO.getId());
        if (existingOrder == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 更新订单基本信息
        if (orderDTO.getCustomer() != null) {
            existingOrder.setCustomer(orderDTO.getCustomer());
        }
        if (orderDTO.getCustomerPhone() != null) {
            existingOrder.setCustomerPhone(orderDTO.getCustomerPhone());
        }
        if (orderDTO.getCustomerAddress() != null) {
            existingOrder.setCustomerAddress(orderDTO.getCustomerAddress());
        }
        if (orderDTO.getTotalAmount() != null) {
            existingOrder.setTotalAmount(orderDTO.getTotalAmount());
        }
        if (orderDTO.getStatus() != null) {
            existingOrder.setStatus(orderDTO.getStatus());
        }
        if (orderDTO.getOperator() != null) {
            existingOrder.setOperator(orderDTO.getOperator());
        }
        if (orderDTO.getRemark() != null) {
            existingOrder.setRemark(orderDTO.getRemark());
        }
        
        // 更新修改时间
        existingOrder.setUpdatedTime(LocalDateTime.now());
        
        // 保存订单基本信息
        orderMapper.update(existingOrder);
        
        // 删除现有的订单详情
        orderDetailMapper.deleteByOrderId(orderDTO.getId());
        
        // 删除现有的出库记录
        stockOutMapper.deleteByOrderId(orderDTO.getId());
        
        // 保存新的订单详情
        if (orderDTO.getOrderDetails() != null && !orderDTO.getOrderDetails().isEmpty()) {
            List<OrderDetail> orderDetails = orderDTO.getOrderDetails().stream()
                    .map(detailDTO -> {
                        OrderDetail detail = new OrderDetail();
                        detail.setOrderId(orderDTO.getId());
                        detail.setProductId(detailDTO.getProductId());
                        detail.setProductName(detailDTO.getProductName());
                        detail.setSpecification(detailDTO.getSpecification());
                        detail.setQuantity(detailDTO.getQuantity());
                        detail.setUnitPrice(detailDTO.getUnitPrice());
                        detail.setTotalPrice(detailDTO.getTotalPrice());
                        detail.setUnit(detailDTO.getUnit());
                        return detail;
                    })
                    .collect(Collectors.toList());

            orderDetailMapper.insertBatch(orderDetails);
        }
        
        // 重新创建出库记录
        createStockOutRecordsFromOrder(orderDTO.getId(), orderDTO.getOrderDetails());
        
        // 返回更新后的订单DTO
        return getOrderWithDetailsById(orderDTO.getId());
    }

    @Override
    @Transactional
    public boolean updateOrderStatus(Long orderId, String status) {
        return orderMapper.updateStatus(orderId, status) > 0;
    }

    @Override
    @Transactional
    public boolean deleteOrder(Long id) {
        // 先删除订单详情
        orderDetailMapper.deleteByOrderId(id);
        // 再删除订单
        return orderMapper.deleteById(id) > 0;
    }

    @Override
    public String generateOrderNumber() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timestamp = LocalDateTime.now().format(formatter);
        return "ORD" + timestamp;
    }
    
    @Override
    public long getOrderCount() {
        return orderMapper.countAll();
    }

    /**
     * 根据订单创建出库记录
     * @param orderId 订单ID
     * @param orderDetails 订单明细列表
     */
    private void createStockOutRecordsFromOrder(Long orderId, List<OrderDetailDTO> orderDetails) {
        if (orderDetails == null || orderDetails.isEmpty()) {
            return;
        }

        List<StockOut> stockOuts = new ArrayList<>();
        
        for (OrderDetailDTO detailDTO : orderDetails) {
            StockOut stockOut = new StockOut();
            stockOut.setOrderId(orderId);
            stockOut.setProductId(detailDTO.getProductId());
            stockOut.setQuantity(detailDTO.getQuantity());
            stockOut.setUnitPrice(detailDTO.getUnitPrice());
            stockOut.setTotalAmount(detailDTO.getTotalPrice());
            stockOut.setCustomer(orderMapper.selectById(orderId).getCustomer());
            stockOut.setOperator(orderMapper.selectById(orderId).getOperator());
            stockOut.setStatus("PENDING"); // 设置为待出库状态
            stockOut.setRemark("订单自动生成");
            
            stockOuts.add(stockOut);
        }

        // 批量保存出库记录
        if (!stockOuts.isEmpty()) {
            stockOutMapper.insertBatch(stockOuts);
        }
    }
} 